
from django import forms
from app.models import User
from django.core.exceptions import ValidationError


class CheckForm(forms.Form):
    username = forms.CharField(max_length=10, min_length=3)
    password = forms.CharField(max_length=13, min_length=6)
    re_password = forms.CharField(max_length=13, min_length=6)
    telephone = forms.CharField(max_length=11, min_length=11)
    email = forms.EmailField()
    birthday = forms.DateField()
    city = forms.CharField()

    def clean_username(self):
        cleaned_username = self.cleaned_data.get('username')
        check_name(cleaned_username)
        return cleaned_username

    def clean(self):
        clean_password = self.cleaned_data.get('password')
        clean_re_password = self.cleaned_data.get('re_password')
        if clean_password != clean_re_password:
            raise ValidationError('两次密码不一致')
        return self.cleaned_data


def check_name(username, is_ajax=False):
    user = User.objects.filter(username=username)
    if is_ajax:
        if  user:
            return  '用户已存在'
        else:
            return 'ok'
    if user:
        raise ValidationError('用户已存在')
